import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbfdrole } from '../../../../atoms/db';

const logger = anylogger('pages/api/admin/role/query.api');

export type IData = ITbfdrole;

export type Result = {
	count: number;
	data: IData[];
};

export type Message = {
	q: string;
	page: string;
	pagesize: string;
}

/**
 * pages/api/admin/role/query.api
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg query:', req.query);
		const { q, ...rest } = req.query as Message;
		const page = Number(rest.page || '1');
		const pagesize = Number(rest.pagesize || '10');
		const dt1 = tbfdrole();

		if (q) {
			const query = q.trim();
			dt1.where('name', 'like', `%${query}%`)
				.orWhere('description', 'like', `%${query}%`);
		}
		const [{ size }] = await dt1.count('*', { as: 'size' });
		const count = Number(size);
		const dt2 = tbfdrole();
		if (q && typeof q === 'string') {
			const query = q.trim();
			dt2.where('name', 'like', `%${query}%`)
				.orWhere('description', 'like', `%${query}%`);
		}
		const offset = (page - 1) * pagesize;
		const d = await dt2
			.select('*')
			.limit(pagesize)
			.offset(offset)
			.orderBy('name', 'asc')
			.orderBy('roleid', 'asc');
		const data = d.map((it) => {
			return {
				...it
			};
		});
		res.status(200).json({ data, count });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ data: [], count: 0 });
	}
});

export const config = {} as PageConfig;

export default handler;
